package logic

import (
	"context"
	"fmt"
	"zhihu/models"
	"zhihu/pkg"

	"zhihu/zhihu_rpc/internal/svc"
	"zhihu/zhihu_rpc/zhihu_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RestLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRestLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RestLogic {
	return &RestLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RestLogic) Rest(in *zhihu_rpc.RestRequest) (*zhihu_rpc.RestResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	key := fmt.Sprintf("%s:phone:%s", "rest", in.Phone)
	get, _ := models.RDB.Get(models.Ctx, key).Result()
	if in.Code != get {
		return nil, fmt.Errorf("验证码错误")
	}
	if models.DB.Where("user_account = ?", in.Account).Limit(1).Find(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if user.ID != 0 {
		return nil, fmt.Errorf("该账号已存在")
	}
	if models.DB.Where("user_phone = ?", in.Phone).Limit(1).Find(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	if user.ID != 0 {
		return nil, fmt.Errorf("手机号已被注册")
	}
	user = models.User{
		UserName:      "",
		UserAccount:   in.Account,
		UserPassword:  pkg.MD5(in.Password),
		UserPhone:     in.Phone,
		UserHandImage: "",
	}
	if models.DB.Create(&user).Error != nil {
		return nil, fmt.Errorf("服务器繁忙")
	}
	return &zhihu_rpc.RestResponse{}, nil
}
